import { adminMenus } from '@/api/system/menu'
import router from '@/router/index'
import { routes } from '@/router/index'
import { errorRoutes, notFound } from '@/router/modules/error'
import { Empty } from 'ant-design-vue'
import common from '@/router/common'
import { RouteRecordRaw } from 'vue-router'
import { RouterTransition } from '@/components/transition'

/**
 * 异步生成菜单树， 方案二
 * @param dataList
 */
const list2tree = (items, pid = 0, pathPrefix = '') => {
  return items
    .filter((item) => item.pid == pid)
    .map((item: any) => {
      const {
        icon,
        id,
        title,
        keepAlive,
        meta,
        filePath,
        key,
        hideChildrenInMenu,
        helpUrl,
        hidden,
        redirect
      } = item
      let path = filePath.startsWith('/') ? filePath : '/' + filePath
      path = filePath.startsWith(pathPrefix) ? path : pathPrefix + path
      path = [...new Set(path.split('/'))].join('/')
      path = path.replace('//', '/')

      // 路由对应的组件
      const component = (() => import(`@/views${path}.vue`)) || Empty

      return {
        // 路由名称，建议唯一
        path: path,
        // 路由名称，建议唯一
        name: key || '',
        children: list2tree(items, id, path),
        // children: hideChildrenInMenu == true ? [] : list2tree(items, id, [], path),
        // 该路由对应页面的 组件 (动态加载)
        component: pid === 0 ? RouterTransition : component,
        props: true,
        hidden: hidden,
        helpUrl: helpUrl,
        hideChildrenInMenu: hideChildrenInMenu,
        redirect: !redirect ? '' : redirect,
        // meta: 页面标题, 菜单图标, 页面权限(供指令权限用，可去掉)
        meta: {
          title: meta?.title || title,
          icon: icon || '',
          // hiddenHeaderContent: hiddenHeaderContent,
          keepAlive: keepAlive == 1,
          reload: false,
          componentName: component.name,
          permission: (key && [key]) || null
        }
      }
    })
    .sort((a, b) => a.sort - b.sort)
}

/**
 * 动态生成菜单
 * @param token
 * @returns {Promise<Router>}
 */
export const generatorDynamicRouter = (): Promise<RouteRecordRaw[]> => {
  return new Promise((resolve, reject) => {
    adminMenus()
      .then((result) => {
        const menuNav: any = []
        const childrenNav = []
        //      后端数据, 根级树数组,  根级 PID
        // listToTree(data, childrenNav, 0)
        // rootRouter.children = childrenNav
        menuNav.push(childrenNav)
        const routeList = list2tree(result)
        // console.log(routeList, '根据后端返回的权限路由生成')
        // routeList.forEach((item) => {
        //   // 设置模块重定向到菜单
        //   if (item.children?.length > 0 && !item.redirect) {
        //     item.redirect = { name: item.children[0].name }
        //   }
        // })
        const layout = routes.find((item) => item.name == 'Layout')!
        layout.children = [...common, ...routeList]
        // const routes = [...common,...routeList]
        // routes.forEach(item => router.addRoute('Layout', item))
        router.addRoute(layout)
        router.addRoute(notFound)
        router.addRoute(errorRoutes)
        resolve(layout.children)
      })
      .catch((err) => {
        console.log(err)
        reject(err)
      })
  })
}
